package com.mobi.Survey;

import java.io.File;
import java.io.IOException;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;

import com.mobi.Survey.utils.Device;
import com.mobi.Survey.utils.Helper;
import com.mobi.Survey.video.GenericPlayer;
import com.mobi.Survey.video.IVideoCallbacks;
import com.mobi.Survey.video.VideoPlayer;
import com.mobi.Survey.video.YouTubeUtility;
import com.mobi.Survey.video.YoutubePlayer;

/**
 * 
 * <b>Author:</b> Yahya Arshad
 * <p>
 * <b>Company:</b> Mobi Media Soft
 * <p>
 * <b> Website:</b> www.mobimediasoft.com
 * <p>
 * VideoScreen.java This class is responsible displaying Video for the product
 * launch this screen with url to the video and type of video i.e youtube or
 * general video on remote server if video with that url already exist on mobile
 * storage drive that video will be played
 */
public class VideoScreen extends AbstractScreen implements IVideoCallbacks {

	private VideoPlayer vp;
	private String url;
	private int type;
	private static boolean playHD = true;

	// If application would unable to play video from youtube it will try to
	// download a video of media format 18 if a youtube video is not available
	// for that type android could not play or download that video
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		hideTitle = true;

		super.onCreate(savedInstanceState);

		Intent intent = getIntent();

		if (intent != null) {
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				String data = (String) bundle.get("data");
				type = Helper.toInt(data.substring(0, 1));
				url = data.substring(1, data.length());
				if (VideoPlayer.TYPE_YOUTUBE == type) {
					vp = new YoutubePlayer(this);
				} else {
					vp = new GenericPlayer(this);
				}
			}

		}
		vp.setVideoCallbackListener(this);
		View v = vp.setupView(2);

		vp.setOnErrorListener(new MediaPlayer.OnErrorListener() {
			public boolean onError(MediaPlayer mp, int framework_err,
					int impl_err) {

				new AlertDialog.Builder(VideoScreen.this)
						.setTitle(Messages.INCOMPATIBLE_VIDEO)
						.setMessage("Press Play for Low Quality Video")
						.setPositiveButton("Play",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										onHDVideoFail();
										// onBtnDownloadVideo();
									}
								})

						.setCancelable(true).show();

				return true;
			}

			private void onHDVideoFail() {
				playHD = false;
				new LongTask().execute(url);

			}
		});
		vp.setMessage(Messages.BUFFERING);
		setContentView(v);
		new LongTask().execute(url);

	}

	@Override
	public void onBackPressed() {

		super.onBackPressed();
		finish();
	}

	@Override
	protected Dialog onCreateDialog(int id) {

		return super.onCreateDialog(id);

	}

	@Override
	protected void initUiVars() {

	}

	@Override
	protected int getLayoutId() {

		return 0;
	}

	// private boolean cancel;

	@Override
	protected void onRelease() {
		printMessage("Stopping Video and Releasing Resources");
		// cancel = true;
		// if (task != null)
		// task.cancel(true);

		vp.stopPlaying();
		vp = null;
	}

	/**
	 * if mobile unable to play youtube video app will try to download video of
	 * media format 18 to
	 * 
	 * @author Yahya Arshad
	 * 
	 */
	// private class YoutubeDownloadTask extends
	// AsyncTask<String, Integer, Object> {
	//
	// String videoPath;
	// String msg;
	//
	// protected Object doInBackground(String... params) {
	// if (cancel)
	// return null;
	// // get youtube id from youtube url
	// String yId = YouTubeUtility.getVideoIdFromUrl(params[0]);
	//
	// // calculate hash value
	// int hash = Helper.getHashNameFromUrl(yId);
	// String tempFile = Helper.getTempFile(hash + "");
	// if (!new File(tempFile).exists())
	// try {
	// if (!Device.isSdPresentForReadWrite()
	// && Device.getAvailableSDSpace() > 50) {
	// msg = Messages.LESS_SPACE_50MB;
	// return null;
	//
	// }
	// videoPath = YouTubeUtility.downloadYoutubeVideo(yId,
	// tempFile);
	//
	// } catch (RuntimeException ex) {
	// msg = ex.getMessage();
	// } catch (Exception e) {
	// msg = e.getMessage();
	// }
	//
	// else {
	// videoPath = tempFile;
	// }
	//
	// return null;
	//
	// }
	//
	// protected void onPostExecute(Object result) {
	//
	// super.onPostExecute(result);
	// if (cancel) {
	//
	// return;
	// }
	// if (videoPath != null && msg == null && !cancel) {
	// vp.showMessage();
	//
	// vp.setMessage(Messages.PLAYING_VIDEO);
	//
	// vp.setUpPlayer(videoPath);
	// vp.startPlaying();
	// } else {
	// showLongToast(msg);
	// vp.dismissTextMessage();
	// vp.dismissProgress();
	// finish();
	//
	// }
	// }
	//
	// protected void onPreExecute() {
	//
	// vp.setMessage(Messages.DOWNLOADING_VIDEO);
	// // vp.showMessage();
	//
	// vp.showProgress();
	//
	// super.onPreExecute();
	//
	// }
	//
	// }

	/**
	 * Preparing and calculating mobile compatible url in background
	 * 
	 * @author Yahya Arshad
	 * 
	 */
	private class LongTask extends AsyncTask<String, Integer, Object> {

		String url;
		String msg;
		private boolean end;

		protected Object doInBackground(String... params) {

			try {
				if (type == VideoPlayer.TYPE_YOUTUBE) {
					String yId = YouTubeUtility.getVideoIdFromUrl(params[0]);
					// int hash = Helper.getHashNameFromUrl(yId);
					// String tempFile = Helper.getTempFile(hash + "");
					// if (!new File(tempFile).exists()) {
					if (playHD) {
						playHD = false;
						url = YouTubeUtility.calculateYouTubeUrl(18, yId);

					} else {

						url = YouTubeUtility.getRTSPUrl(yId);
						end = true;
					}
					// } else {
					// url = tempFile;
					// }
				} else {
					int hash = Helper.getHashNameFromUrl(params[0]);

					String tempFile = Helper.getTempFile(hash + "");
					if (!new File(tempFile).exists()) {
						url = params[0];

					} else {
						url = tempFile;
					}

				}
			} catch (NullPointerException ex) {
				msg = Messages.NO_RTSP_LINK;
			} catch (IOException ex) {
				msg = Messages.VIDEO_IO_ERROR;
			} catch (Exception ex) {
				msg = Messages.INVALID_VIDEO_URL;
			}

			return null;

		}

		protected void onPostExecute(Object result) {

			super.onPostExecute(result);

			if (url != null && vp != null) {

				vp.setUpPlayer(url);
				vp.startPlaying();
			} else if (msg != null && end) {
				showLongToast(msg);
				finish();
			}

		}

		protected void onPreExecute() {

			super.onPreExecute();

		}

	}

	// YoutubeDownloadTask task;

	protected void onBtnDownloadVideo() {
		// if (VideoPlayer.TYPE_YOUTUBE == type) {
		// task = new YoutubeDownloadTask();
		// task.execute(url);
		// } else {
		// showLongToast(Messages.UNABLE_TOP_PLAY_GENERIC_VIDEO + url);
		// finish();
		// }
	}

	@Override
	public void onPrepare() {

	}

}
